package com.tanglon.controller;

import com.tanglon.domain.ResponseResult;
import com.tanglon.enums.AppHttpCodeEnum;
import com.tanglon.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public ResponseResult uploadImg(MultipartFile img) {
        try {
            //原始文件名
            String originalFilename = img.getOriginalFilename();
            //截取原始文件后缀名
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新的文件名称
            String objectName = UUID.randomUUID().toString() +extName;

            String url = aliOssUtil.upload(img.getBytes(), objectName);
            return ResponseResult.okResult(url);
        } catch (IOException e) {
            //文件上传失败
            e.printStackTrace();

        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }
}
